const logModel = require('../models/logs.model')
const logger = require('../utils/logger')
class LogService {
  logs = logModel
  async findAll ({ page = 1, pageSize = 100, type, ref, operateDate }) {
    const query = {
      deleted: false,
    }

    if (type) {
      query.type = type
    }
    if (ref) {
      query.ref = ref
    }
    if (operateDate) {
      if (typeof operateDate === 'object') {
        query.operateDate = operateDate
      } else {
        let start = new Date(operateDate).format('yyyy-MM-dd 00:00:00')
        let end = new Date(operateDate).format('yyyy-MM-dd 23:59:59')
        query.operateDate = {
          $gte: start,
          $lte: end
        }
      }
    }
    const sort = {
      operateDate: -1
    }
    page = parseInt(page) || 1
    const limit = parseInt(pageSize) || 100
    const skip = (page - 1) * (limit)
    const data = await this.logs.find(query).sort(sort).skip(skip).limit(limit).populate('operator').populate({
      path: 'ref',
      populate: { path: 'registration' }
    })
    const totalSize = await this.logs.countDocuments(query)
    return {
      data,
      totalSize
    }
  }
  findOne (id) {
    return this.logs.find({ deleted: false, _id: id })
  }
  updateOne (id, data) {
    return this.logs.findOneAndUpdate({ _id: id }, data)
  }
  deleteOne (id) {
    return this.logs.findOneAndUpdate({ _id: id }, { deleted: true })
  }
  async addOne (doc) {
    // TODO check doc
    logger.info('log created ', doc)
    return await this.logs.create(doc)
  }
}

module.exports = LogService